package com.example.vertification.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.entity.User;
import com.example.vertification.entity.Order;
import com.example.vertification.service.OrderService;
import com.example.vertification.service.RegisterCodeService;
import com.example.vertification.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private static Set<WebSocketSession> sessions = new HashSet<>();
    private HashMap<String,WebSocketSession> map = new HashMap<String,WebSocketSession>();
    private HashMap<WebSocketSession,String> map2 = new HashMap<WebSocketSession,String>();

    @Autowired
    private UserService userService; // 自动注入 UserService 实例

    @Autowired
    private OrderService orderService; // 自动注入 UserService 实例



    public WebSocketHandler(UserService userService,OrderService orderService) {
        this.userService = userService;
        this.orderService=orderService;
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JSONObject obj = JSONUtil.parseObj(message.getPayload());

        if(obj.getStr("action").equalsIgnoreCase("initialize")){
            JSONObject dataObj = obj.getJSONObject("data");
            String token = dataObj.getStr("token");
            User u = userService.getUserByToken(token);
            if(u==null){
                return;
            }
            this.map.put(String.valueOf(u.getUid()),session);
            this.map2.put(session, String.valueOf(u.getUid()));
            return;
        }

        if(obj.getStr("action").equalsIgnoreCase("send_to_other")){

            JSONObject dataObj = obj.getJSONObject("data");
            String content = dataObj.getStr("content");
            //发给谁
            String who_uid = dataObj.getStr("who_uid");
            //通过session获得发起人
            String send_uid = map2.get(session);
            System.out.println(who_uid);
            System.out.println(map);
            WebSocketSession wss = map.get(who_uid);
            if(wss==null){
                session.sendMessage(new TextMessage("tip|该用户当前未在线,已发送至留言"));
            }else{
                wss.sendMessage(new TextMessage("receive|"+send_uid+","+content));
            }
        }

        System.out.println(obj);
        if(obj.getStr("action").equalsIgnoreCase("update_order")){

            JSONObject dataObj = obj.getJSONObject("data");
            //发给谁
            String ordernum = dataObj.getStr("ordernum");
            //通过session获得发起人
            String send_uid = map2.get(session);
            if(send_uid==null){
                session.sendMessage(new TextMessage("tip|登录状态异常,无法发送WebSocket通信发包"));
                return;
            }

            Order order = orderService.getOrderByOrderNum(ordernum);

            if(order.getProductBuyerUid() != Long.parseLong(send_uid) && order.getProductSellerUid() != Long.parseLong(send_uid)){
                session.sendMessage(new TextMessage("tip|此订单与你无关,无法发送WebSocket通信发包"));
                return;
            }

            boolean is_buy = false;
            if(order.getProductBuyerUid() == Long.parseLong(send_uid)){
                is_buy = true;
            }


            WebSocketSession wss;
            if(is_buy){
                wss = map.get(String.valueOf(order.getProductSellerUid()));
            }else{
                wss = map.get(String.valueOf(order.getProductBuyerUid()));
            }

            if(wss!=null){
                wss.sendMessage(new TextMessage("tip|您的订单状态已被对方操作,请刷新"));
            }
        }



    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }
}
